chrome.extension.onRequest.addListener(function (request, sender, sendResponse) {
  var res = messageHandler[request.type](request, sender);
  sendResponse(res);
});

var messageHandler = {
  fillPassword: function(request, sender) {
    if(passwordBox != null) {
      passwordBox.val(request.password);
      passwordBox.blur();
    }
  }
};

var passwordBox;
function RequestPassword() {
  passwordBox = $(this);
  chrome.extension.sendRequest(
    {
      type: "requestPassword",
      domain: window.location.hostname
    },
    function(response) {}
  );
}

var infobarPort = null;
chrome.extension.onConnect.addListener(function(port) {
  infobarPort = port;
  port.onMessage.addListener(function(msg) {
    messageHandler[msg.type](msg, infobarPort);
  });
  port.onDisconnect.addListener(function() {
    infobarPort = null;
  });
});

function CloseInfoBar() {
  if(infobarPort != null) {
    infobarPort.postMessage({type: "close"});
  }
}

var eventInPassword = false;
$("input:password")
.click(
  function() {
    eventInPassword = true;
  }
)
.focusin(
  function() {
    eventInPassword = true;
    RequestPassword.call(this);
  }
);

$(window)
.bind('click focusin', function() {
  if(!eventInPassword) {
    CloseInfoBar();
  }
  eventInPassword = false;
});

